<template>
  <div class="writeScene">
    <header>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/sensorHome' }" class="homePage">传感器类型管理</el-breadcrumb-item>
        <el-breadcrumb-item>添加</el-breadcrumb-item>
      </el-breadcrumb>
    </header>
    <div class="title">添加传感器类型</div>
    <div class="main">
      <div class="header">
        <span></span>
        <p>传感器信息</p>
      </div>
      <div class="mainFrom">
        <el-form
          :model="addSensorParams"
          :rules="rules"
          ref="addSensorParams"
          label-width="300px"
          class="demo-ruleForm"
        >
          <el-form-item prop="sceneTypeName" label="传感器类型名称：" >
            <el-input v-model="addSensorParams.sceneTypeName" maxlength="20"></el-input>
          </el-form-item>
          <el-form-item prop="sensorType" label="监测类型名称：" >
            <el-input v-model="addSensorParams.sensorType" maxlength="10"></el-input>
          </el-form-item>
          <el-form-item prop="imageList" label="传感器图标：">
            <el-upload
              :action="uploadImg"
              list-type="picture-card"
              :before-upload="beforeUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :headers="headOfRequest"
              :with-credentials="true"
              :limit="1"
              :file-list="addSensorParams.imageList"
              ref="elUpload"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <p class="addTips">*图标尺寸：108px*108px，格式为png；</p>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt />
            </el-dialog>
          </el-form-item>
          <el-form-item  label="设备描述 :" >
            <el-input
              type="textarea"
              placeholder="请输入设备描述"
              v-model="addSensorParams.deviceTypeDesc"
              maxlength="50"
              :rows="8"
              style="width:560px"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <footer>
        <div class="title">
          <div class="left">
            <span></span>
            <p>传感器监测数据管理</p>
          </div>
          <div class="addSensorInfo" @click="addBox">添加</div>
        </div>
        <table class="dataInfo" border="0" cellspacing="0" cellpadding="0">
          <thead class="dataHead">
            <th>数据名称</th>
            <th>单位</th>
            <th>键值</th>
            <th>操作</th>
          </thead>
          <tbody class="dataBody" v-show="deviceTable.length !== 0">
            <tr v-for="(item,index) in deviceTable" :key="index">
              <td>{{item.natureValue}}</td>
              <td>{{item.natureUnit}}</td>
              <td>{{item.natureKey}}</td>
              <td>
                <span class="write" @click="writeMonitor(index)">编辑</span>
                <span class="delete" @click="deleteMonitor(index)">删除</span>
              </td>
            </tr>
          </tbody>
        </table>
        <div class="emptyTbody" v-show="deviceTable.length === 0">暂无数据</div>
        <!-- 导航栏 -->
        <div class="block" v-if="deviceTable.length !== 0">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            :page-size="5000"
            layout="total, prev, pager, next, jumper"
            :total="deviceTable.length"
          ></el-pagination>
        </div>
        <span class="addOne" v-show="isAddOne">请添加至少一个传感器监测数据</span>
        <div class="determain">
          <div class="btn" @click="determainAddDevice">确定</div>
        </div>
      </footer>
      <!-- 添加盒子 -->
      <div class="addbox" v-if="this.$store.state.sensor.showAddBox&&this.$store.state.ifShowCover">
        <div class="boxHeader">
          <p>添加设备监测数据</p>
          <i class="el-icon-close" @click="closeAddBox"></i>
        </div>
        <div class="addMainBox">
          <el-form
            :model="deviceMonitorList"
            :rules="rules"
            ref="deviceMonitorList"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item prop="natureValue" label="数据名称 :" class="name">
              <el-input v-model="deviceMonitorList.natureValue" maxlength="10"></el-input>
            </el-form-item>
            <el-form-item prop="natureUnit" label="单位 :" class="unit">
              <el-input v-model="deviceMonitorList.natureUnit"></el-input>
            </el-form-item>
            <el-form-item prop="natureKey" label="键值 :" class="associateKey">
              <el-input v-model="deviceMonitorList.natureKey"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <footer>
          <div class="cancel" @click="closeAddBox">取消</div>
          <div class="determainAdd" @click="determainAdd">确定</div>
        </footer>
      </div>
      <!-- 编辑盒子 -->
      <div
        class="addbox"
        v-if="this.$store.state.sensor.showWriteBox&&this.$store.state.ifShowCover">
        <div class="boxHeader">
          <p>编辑设备监测数据</p>
          <i class="el-icon-close" @click="closeAddBox"></i>
        </div>
        <div class="addMainBox">
          <el-form
            :model="writeParams"
            :rules="rules"
            ref="writeParams"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item prop="natureValue" label="数据名称 :" class="name">
              <el-input v-model="writeParams.natureValue" maxlength="10"></el-input>
            </el-form-item>
            <el-form-item prop="natureUnit" label="单位 :" class="unit">
              <el-input v-model="writeParams.natureUnit"></el-input>
            </el-form-item>
            <el-form-item prop="natureKey" label="键值 :" class="associateKey">
              <el-input v-model="writeParams.natureKey"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <footer>
          <div class="cancel" @click="closeAddBox">取消</div>
          <div class="determainAdd" @click="determainWrite">确定</div>
        </footer>
      </div>
    </div>
  </div>
</template>

<script>
import { uploadImg, deleteImg } from '../../../api/file'
import { getToken } from '../../../utils/token'
import { DeviceTypeAdd } from '../../../api/sensor'

export default {
  data () {
    return {
      // 上传图片的url地址
      uploadImg: uploadImg,
      // 上传图片组件的请求头设置
      headOfRequest: { token: getToken() },
      imageUrl: '',
      addSensorParams: {
        sceneTypeName: '',
        sensorType: '',
        imageList: [],
        deviceTypeDesc: '',
        imageUrl: ''
      },
      deviceMonitorList: {
        natureKey: '',
        natureUnit: '',
        natureValue: ''
      },
      deviceTable: [],
      dialogImageUrl: '',
      dialogVisible: false,
      rules: {
        sceneTypeName: [
          { required: true, message: '请输入', trigger: 'blur' },
          {
            min: 1,
            max: 20,
            message: '长度需小于20个字符',
            trigger: ['blur', 'change']
          }
        ],
        sensorType: [
          { required: true, message: '请输入', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '长度需小于10个字符',
            trigger: ['blur', 'change']
          }
        ],
        imageList: [
          { required: true, message: '请添加封面', trigger: 'change' }
        ],
        natureValue: [
          { required: true, message: '请输入数据名称' },
          {
            min: 1,
            max: 10,
            message: '长度需小于10个字符',
            trigger: ['blur', 'change']
          }
        ],
        natureUnit: [
          { required: true, message: '请输入单位' },
          {
            min: 1,
            max: 10,
            message: '长度需小于10个字符',
            trigger: ['blur', 'change']
          }
        ],
        natureKey: [
          { required: true, message: '请输入键值' },
          {
            min: 1,
            max: 10,
            message: '长度需小于10个字符',
            trigger: ['blur', 'change']
          }
        ],
        isShow: [{ required: true, message: '请选择' }]
      },
      currentPage: +'',
      isAddOne: false,
      writeParams: [],
      WriteIndex: ''
    }
  },
  methods: {
    beforeUpload (file) {
      const testmsg = /^image\/(jpg|JPG|jpeg|png|PNG|bmp|BMP)$/.test(file.type)
      const isLT3M = file.size / 1024 / 1024 <= 3
      if (!testmsg) {
        this.$message.error('图片格式错误')
        return false
      }
      if (!isLT3M) {
        this.$message.error('上传图片大小不能超过3M!')
        return false
      }
      return testmsg && isLT3M
    },
    // 图片上传成功的钩子
    handleSuccess (res, file, fileList) {
      // console.log(res)
      this.imageUrl = res.data.id
      const arr = this.$refs.elUpload.$children[1].$el.classList
      arr.add('hidden')
      this.addSensorParams.imageList = fileList
    },
    // 图片移除成功的钩子
    handleRemove (file, fileList) {
      const arr = this.$refs.elUpload.$children[1].$el.classList
      arr.remove('hidden')
      this.addSensorParams.imageList = []
      deleteImg(12, file.response.data.url)
    },
    // 查看大图的钩子
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleCurrentChange (val) {
      // console.log(val)
    },
    addBox () {
      this.$store.state.ifShowCover = true
      this.deviceMonitorList = {
        natureKey: '',
        natureUnit: '',
        natureValue: ''
      }
      this.$store.commit('sensor/show_addBox', true)
    },
    closeAddBox () {
      this.$store.state.ifShowCover = false
      this.$store.commit('sensor/show_addBox', false)
      this.$store.commit('sensor/show_writeBox', false)
    },
    determainAdd () {
      this.isAddOne = false
      this.$refs.deviceMonitorList.validate(valid => {
        if (valid) {
          this.deviceTable.push(this.deviceMonitorList)
          this.$store.state.ifShowCover = false
          this.$store.commit('sensor/show_addBox', false)
          this.deviceMonitorList = {}
        }
      })
    },
    // 确定编辑
    determainWrite () {
      this.deviceTable[this.WriteIndex] = this.writeParams
      this.$store.state.ifShowCover = false
      this.$store.commit('sensor/show_writeBox', false)
    },
    // 确定添加设备类型
    async determainAddDevice () {
      this.$refs.addSensorParams.validate(valid => {
        if (!valid) {
          return false
        }
      })
      if (this.deviceTable.length === 0) {
        this.isAddOne = true
        return
      }
      const params = {
        deviceCheckType: this.addSensorParams.sensorType,
        deviceMonitorList: this.deviceTable,
        deviceTypeDesc: this.addSensorParams.deviceTypeDesc,
        deviceTypeImg: this.imageUrl,
        deviceTypeName: this.addSensorParams.sceneTypeName
      }
      const { data: res } = await DeviceTypeAdd(params)
      // console.log(res)
      if (res.code === 200) {
        this.$message({
          message: res.message,
          type: 'success',
          duration: 500
        })
        this.$router.push('/sensorHome')
      } else {
        this.$message({
          message: res.message,
          type: 'error',
          duration: 1500
        })
      }
    },
    deleteMonitor (index) {
      this.deviceTable.splice(index, 1)
    },
    writeMonitor (index) {
      this.WriteIndex = index
      this.$store.state.ifShowCover = true
      this.$store.commit('sensor/show_writeBox', true)
      this.$store.commit('sensor/show_addBox', false)
      this.writeParams = this.deviceTable[this.WriteIndex]
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../../../styles/sensor.scss";
@import "../../../styles/writeBox.scss";
.main{
  .mainFrom{
    height: auto !important;
  }
  ::v-deep .el-form{
    .el-input{
      width: 400px;
    }
    .el-form-item__content{
      line-height: unset;
    }
    .el-form-item__error{
      left: 300px;
      line-height: 24px;
    }
    .el-form-item{
      margin-bottom: 32px;
    }
    .el-form-item__label{
      width: 300px !important;
    }
    .el-upload-list--picture-card .el-upload-list__item{
      margin-bottom: 0;
    }
    .addTips{
      position: absolute;
      left: 465px;
      top: 10px;
      height:20px;
      font-size:14px;
      font-family:PingFangSC-Regular,PingFang SC;
      font-weight:400;
      color:rgba(255,180,21,1);
      line-height:20px;
          }
  }
}
  table {
    position: relative;
    margin-top: 20px;
    width: 96%;
    text-align: left;
      thead {
        font-weight: 500;
        font-size: 14px;
        background: rgba(87, 131, 255, 0.05);
        th {
          color: rgba(51, 51, 51, 1);
          height: 60px;
          line-height: 60px;
          text-align: left;
          padding-left: 24px;
          border-bottom: solid 1px rgba(230, 230, 230, 1);
        }
      }
    tbody {
      tr {
        height: 64px;
        td {
          font-size: 14px;
          font-weight: 400;
          color: rgba(102, 102, 102, 1);
          padding-left: 24px;
          border-bottom: solid 1px #f2f2f2;
          .write {
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            color: rgba(72, 104, 255, 1);
            text-decoration: underline;
          }
          .delete {
            cursor: pointer;
            margin-left: 24px;
            font-size: 14px;
            font-weight: 500;
            color: #fb4646;
            text-decoration: underline;
          }
        }
      }
    }
  }
</style>
